<template>
  <div class="app-container">
    <el-form ref="formRef" :disabled="!editAble" :model="form" :rules="rules" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="出入仓类型" prop="inOrderType">
            <el-select v-if="editAble" v-model="form.inOrderType" placeholder="出入仓类型" disabled>
              <el-option
                v-for="dict in inout_storehouse"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <dict-tag v-else :options="inout_storehouse" :value="form.inOrderType" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="调拨单编号" prop="moveCode">
            <code-input
              v-if="editAble"
              v-model="form.moveCode"
              code="MOVE_INVENTORY_CODE"
              :disabled="!!form.id"
              placeholder="请输入调拨单编号"
            />
            <el-tooltip v-else effect="dark" :content="form.moveCode">
              <div class="form-text">{{ form.moveCode }}</div>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="调拨单名称" prop="moveName">
            <el-input v-if="editAble" v-model="form.moveName" placeholder="请输入调拨单名称" />
            <el-tooltip v-else effect="dark" :content="form.moveName">
              <div class="form-text">{{ form.moveName }}</div>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <SearchTool
          v-if="editAble"
          :disabled='operationTitle.indexOf("编辑")>-1'
          :code="{
            factory: 'factory',
          }"
          :titles="{
            factory: '工厂',
            workshop: '工段',
            line: '产线',
            section: '工艺段',
          }"
          :layout="true"
          :span="6"
          v-model:factory="form.factory"
          :showWorkshop="false"
          :showLine="false"
          :showSection="false"
        ></SearchTool>
        <el-col v-else :span="6">
          <el-form-item label="工厂" prop="factory">
            <div class="form-text">{{ form.factoryName }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="调拨原因" prop="moveReason">
            <el-input
              v-if="editAble"
              v-model="form.moveReason"
              type="textarea"
              :maxlength="200"
              show-word-limit
              placeholder="请输入调拨原因"
            />
            <div v-else class="form-text">{{ form.moveReason }}</div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="调拨明细" name="first">
        <el-row v-if="editAble" :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="plus"
              v-hasPermi="['warehouse:movehouse:edit']"
              @click="handleAddWhStorehouseInDetail"
            >
              选择物料
            </el-button>
          </el-col>
          <el-col v-if="editAble" :span="1.5" class="top-right-btn">
            <el-button
              type="primary"
              v-hasPermi="['warehouse:movehouse:edit']"
              link
              @click="batchSetting"
            >
              批量设置线边仓、库位
            </el-button>
          </el-col>
        </el-row>
        <el-form ref="tableForm" :model="whMoveInventoryDetailList" label-width="0">
          <el-table
            :data="whMoveInventoryDetailList"
            border
            maxHeight="400"
            :row-class-name="rowWhStorehouseInDetailIndex"
            ref="whStorehouseInDetail"
          >
            <el-table-column label="序号" align="center" prop="index" width="80" />
            <el-table-column label="物料/产品名称" prop="matName" width="150" />
            <el-table-column label="物料/产品编号" prop="matCode" width="150" />

            <el-table-column label="批次号" prop="batchNo" width="150" />
            <el-table-column label="调拨前" align="center">
              <el-table-column label="工段" prop="moveFrontWorkSectionName" width="150" />

              <el-table-column label="产线" prop="moveFrontPdcLineName" width="150" />
              <el-table-column label="工艺段" prop="moveFrontProcessSectionName" width="150" />

              <el-table-column label="线边仓" prop="moveFrontWorkshopName" width="150" />

              <el-table-column label="库位" prop="moveFrontWarehouseName" width="150" />

              <el-table-column label="库存" prop="moveFrontStockNum" width="150"></el-table-column>
              <el-table-column label="冻结库存" prop="frozenNum"></el-table-column>
              <el-table-column label="可用库存" prop="availableNum"></el-table-column>
            </el-table-column>

            <el-table-column label="调拨数量" prop="moveNum" width="150">
              <template v-if="editAble" #header>
                <span style="color: red">*</span>
                <span>调拨数量</span>
              </template>
              <template v-if="editAble" #default="scope">
                <el-form-item
                  label=""
                  :prop="`[${scope.$index}].moveNum`"
                  :rules="[
                    {
                      required: true,
                      message: '请输入数量',
                      trigger: 'blur',
                    },
                  ]"
                  style="margin-top: 15px; margin-bottom: 15px"
                >
                  <el-input-number
                    v-model="scope.row.moveNum"
                    controls-position="right"
                    :min="0"
                    :max="scope.row.availableNum"
                  >
                    <template #decrease-icon>
                      <el-icon>
                        <Minus />
                      </el-icon>
                    </template>
                    <template #increase-icon>
                      <el-icon>
                        <Plus />
                      </el-icon>
                    </template>
                  </el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="单位" prop="packageUnit" width="150" />
            <el-table-column label="调拨后" align="center">
              <el-table-column label="工段" prop="moveAfterWorkSectionName" width="150">
                <template v-if="editAble" #header>
                  <span style="color: red">*</span>
                  <span>工段</span>
                </template>
                <template v-if="editAble" #default="scope">
                  <el-form-item
                    label=""
                    :prop="`[${scope.$index}].moveAfterWorkSection`"
                    :rules="[
                      {
                        required: true,
                        message: '请选择工段',
                        trigger: ['blur', 'change'],
                      },
                    ]"
                    style="margin-top: 15px; margin-bottom: 15px"
                  >
                    <DeptSelect
                      v-model="scope.row.moveAfterWorkSection"
                      type="workshop"
                      :parent="form.factory"
                      :key="`workshop-${scope.$index}`"
                      @change="workshopChange(scope.row)"
                      placeholder="请选择工段"
                    ></DeptSelect>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="产线" prop="moveAfterPdcLineName" width="150">
                <template v-if="editAble" #header>
                  <span style="color: red">*</span>
                  <span>产线</span>
                </template>
                <template v-if="editAble" #default="scope">
                  <el-form-item
                    label=""
                    :prop="`[${scope.$index}].moveAfterPdcLine`"
                    :rules="[
                      {
                        required: true,
                        message: '请选择产线',
                        trigger: ['blur', 'change'],
                      },
                    ]"
                    style="margin-top: 15px; margin-bottom: 15px"
                  >
                    <DeptSelect
                      v-model="scope.row.moveAfterPdcLine"
                      type="line"
                      :key="`prodLine-${scope.$index}`"
                      :parent="scope.row.moveAfterWorkSection"
                      @change="lineChange(scope.row)"
                      placeholder="请选择产线"
                    ></DeptSelect>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="工艺段" prop="moveAfterProcessSectionName" width="150">
                <template v-if="editAble" #header>
                  <span>工艺段</span>
                </template>
                <template v-if="editAble" #default="scope">
                  <el-form-item label="" style="margin-top: 15px; margin-bottom: 15px">
                    <DeptSelect
                      v-model="scope.row.moveAfterProcessSection"
                      type="section"
                      :key="`prodSection-${scope.$index}`"
                      :parent="scope.row.moveAfterPdcLine"
                      @change="sectionChange(scope.row)"
                      placeholder="请选择工艺段"
                    ></DeptSelect>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="线边仓" prop="moveAfterWorkshopName" width="150">
                <template v-if="editAble" #header>
                  <span style="color: red">*</span>
                  <span>线边仓</span>
                </template>
                <template v-if="editAble" #default="scope">
                  <el-form-item
                    label=""
                    :prop="`[${scope.$index}].moveAfterWorkshopCode`"
                    :rules="[
                      {
                        required: true,
                        message: '请选择线边仓',
                        trigger: ['blur', 'change'],
                      },
                    ]"
                    style="margin-top: 15px; margin-bottom: 15px"
                  >
                    <StoreSelect
                      v-model="scope.row.moveAfterWorkshopCode"
                      :key="`moveAfterWorkshopCode-${scope.$index}`"
                      :line="scope.row.moveAfterPdcLine"
                      :section="scope.row.moveAfterProcessSection"
                      @change="storeChange(scope.row)"
                      placeholder="请选择线边仓段"
                      title="选择线边仓"
                    ></StoreSelect>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="库位" prop="moveAfterWarehouseName" width="150">
                <template v-if="editAble" #header>
                  <span style="color: red">*</span>
                  <span>库位</span>
                </template>
                <template v-if="editAble" #default="scope">
                  <el-form-item
                    label=""
                    :prop="`[${scope.$index}].moveAfterWarehouse`"
                    :rules="[
                      {
                        required: true,
                        message: '请选择库位',
                        trigger: ['blur', 'change'],
                      },
                    ]"
                    style="margin-top: 15px; margin-bottom: 15px"
                  >
                    <BinSelect
                      v-model="scope.row.moveAfterWarehouse"
                      :key="`bin-${scope.$index}`"
                      :parent="scope.row.moveAfterWorkshopCode"
                      placeholder="请选择库位"
                    ></BinSelect>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column
              v-if="editAble"
              label="操作"
              align="center"
              fixed="right"
              minWidth="100"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  link
                  icon="delete"
                  type="primary"
                  @click="handleDeleteWhStorehouseInDetail(scope.row, scope.$index)"
                  v-hasPermi="['warehouse:inStorehouse:remove']"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <moveDialog
      v-model:show="show"
      :value="whMoveInventoryDetailList"
      :factory="form.factory"
      @change="handleChange"
    ></moveDialog>
    <el-dialog
      title="批量设置线边仓、库位"
      v-model="showSetting"
      width="700px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form ref="settingDialog" :model="settingForm" :rules="settingRules" label-width="100px">
        <el-form-item label="工段" prop="workshopCode">
          <DeptSelect
            v-model="settingForm.workshopCode"
            type="workshop"
            :parent="form.factory"
            :key="`workshop`"
            @change="workshopChange(settingForm, '0')"
            placeholder="请选择工段"
          ></DeptSelect>
        </el-form-item>
        <el-form-item label="产线" prop="productLine">
          <DeptSelect
            v-model="settingForm.productLine"
            type="line"
            :key="`prodLine`"
            :parent="settingForm.workshopCode"
            @change="lineChange(settingForm, '0')"
            placeholder="请选择产线"
          ></DeptSelect>
        </el-form-item>
        <el-form-item label="工艺段" prop="sectionCode">
          <DeptSelect
            v-model="settingForm.sectionCode"
            type="section"
            :key="`prodSection`"
            :parent="settingForm.productLine"
            @change="sectionChange(settingForm, '0')"
            placeholder="请选择工艺段"
          ></DeptSelect>
        </el-form-item>
        <el-form-item label="线边仓" prop="storehouse">
          <StoreSelect
            v-model="settingForm.storehouse"
            :key="`storehouse`"
            :line="settingForm.productLine"
            :section="settingForm.sectionCode"
            @change="storeChange(settingForm, '0')"
            placeholder="请选择线边仓段"
            title="选择线边仓"
          ></StoreSelect>
        </el-form-item>
        <el-form-item label="库位" prop="bin">
          <BinSelect
            v-model="settingForm.bin"
            :key="`bin`"
            :parent="settingForm.storehouse"
            placeholder="请选择库位"
          ></BinSelect>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSetting">确 定</el-button>
          <el-button @click="cancelSetting">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="warehouse">
import {
  getMoveInventory,
  addMoveInventory,
  confirmMoveInventory,
  listMoveInventoryDetail,
  delMoveInventoryDetail,
} from "@/api/warehouse/moveInventory";
import { reactive, toRefs, useAttrs, getCurrentInstance, ref, onMounted } from "vue";
import moveDialog from "./components/moveDialog.vue";
import {floatSub} from "@/utils/mathCount"
const attrs = useAttrs();
const { proxy } = getCurrentInstance();
const activeName = ref("first");
const { inout_storehouse } = proxy.useDict("inout_storehouse");
const operationTitle = ref("");
const isBatch = ref(false);
const refData = reactive({
  // 表单参数
  form: {},
  settingForm: {},
  // 表单校验
  rules: {
    moveCode: [{ required: true, message: "调拨单编号不能为空", trigger: "blur" }],
    moveName: [{ required: true, message: "调拨单名称不能为空", trigger: "blur" }],
    factory: [{ required: true, message: "工厂不能为空", trigger: "change" }],
  },
  settingRules: {
    workshopCode: [{ required: true, message: "工段不能为空", trigger: "change" }],
    productLine: [{ required: true, message: "产线不能为空", trigger: "change" }],
    storehouse: [{ required: true, message: "线边仓不能为空", trigger: "change" }],
    bin: [{ required: true, message: "库位不能为空", trigger: "change" }],
  },
});
const { form, rules, settingForm, settingRules } = toRefs(refData);
const emit = defineEmits(["close", "setActions", "setIsActionTop"]);
const whMoveInventoryDetailList = ref([]);
const formRef = ref("formRef");
const tableForm = ref("tableForm");
const show = ref(false);
const editAble = ref(false);
const binEditAble = ref(false);
const actions = ref([
  {
    text: "取 消",
    theme: "",
    handle: () => {
      cancel();
    },
  },
  {
    text: "确 定",
    theme: "primary",
    handle: () => {
      submitForm();
    },
    loading: false,
  },
]);
const showSetting = ref(false);

const settingDialog = ref("settingDialog");
const batchSetting = () => {
  if (!whMoveInventoryDetailList.value.length) {
    proxy.$modal.msgError("请先添加物料");
    return;
  }
  showSetting.value = true;
};

const submitSetting = () => {
  settingDialog.value.validate((valid) => {
    if (valid) {
      whMoveInventoryDetailList.value.forEach((el) => {
        el.moveAfterWorkSection = settingForm.value.workshopCode;
        el.moveAfterPdcLine = settingForm.value.productLine;
        el.moveAfterProcessSection = settingForm.value.sectionCode;
        el.moveAfterWorkshopCode = settingForm.value.storehouse;
        el.moveAfterWarehouse = settingForm.value.bin;
      });
      showSetting.value = false;
    }
  });
};
const cancelSetting = () => {
  showSetting.value = false;
};
// 取消按钮
function cancel() {
  emit("close");
}

function workshopChange(row, type) {
  if (!type) {
    row.moveAfterPdcLine = "";
    row.moveAfterProcessSection = "";
    row.moveAfterWorkshopCode = "";
    row.moveAfterWarehouse = "";
  } else {
    row.productLine = "";
    row.sectionCode = "";
    row.storehouse = "";
    row.bin = "";
  }
}

function lineChange(row, type) {
  if (!type) {
    row.moveAfterProcessSection = "";
    row.moveAfterWorkshopCode = "";
    row.moveAfterWarehouse = "";
  } else {
    row.sectionCode = "";
    row.storehouse = "";
    row.bin = "";
  }
}
function sectionChange(row, type) {
  if (!type) {
    row.moveAfterWorkshopCode = "";
    row.moveAfterWarehouse = "";
  } else {
    row.storehouse = "";
    row.bin = "";
  }
}
function storeChange(row, type) {
  if (!type) {
    row.moveAfterWarehouse = "";
  } else {
    row.bin = "";
  }
}

// 表单重置
function reset() {
  form.value = {
    factory: "",
    inOrderType: "7",

    moveCode: "",

    moveName: "",
    moveReason: "",
    moveTime: "",
    remark: "",
    status: "",
    whMoveInventoryDetailList: [],
  };
  formRef.value.resetFields();
  whMoveInventoryDetailList.value = [];
}

/** 修改按钮操作 */
function getDetail(id) {
  getMoveInventory(id).then((response) => {
    form.value = response.data;
    form.value.inOrderType = "7";
    getListWhStorehouseInDetail(response.data.moveCode);
  });
}

/** 提交按钮 */
function submitForm() {
  if (operationTitle.value == "确认调拨") {
    if (whMoveInventoryDetailList.value.length) {
      tableForm.value.validate((result) => {
        if (result) {
          proxy.$modal.confirm("是否提交确认调拨单？").then(() => {
            form.value.whMoveInventoryDetailList = whMoveInventoryDetailList.value;
            addMoveInventory(form.value).then(() => {
              confirmMoveInventory(form.value.id).then(() => {
                proxy.$modal.msgSuccess("提交成功");
                cancel();
              });
            });
          });
        }
      });
    } else {
      proxy.$modal.msgError("请添加物料");
    }
  } else {
    formRef.value.validate((valid) => {
      if (valid) {
        if (whMoveInventoryDetailList.value.length) {
          tableForm.value.validate((result) => {
            if (result) {
              proxy.$modal.confirm("是否提交调拨单？").then(() => {
                form.value.whMoveInventoryDetailList = whMoveInventoryDetailList.value;
                addMoveInventory(form.value).then(() => {
                  proxy.$modal.msgSuccess("提交成功");
                  cancel();
                });
              });
            }
          });
        } else {
          proxy.$modal.msgError("请添加物料");
        }
      }
    });
  }
}

/** 物料调拨明细序号 */
function rowWhStorehouseInDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}
/** 物料调拨明细添加按钮操作 */
function handleAddWhStorehouseInDetail() {
  formRef.value.validate((valid) => {
    if (valid) {
      show.value = true;
    }
  });
}
function handleChange(val) {
  if (val.length) {
    let _newArr = [];
    let randomIdList = [];
    whMoveInventoryDetailList.value.forEach((info) => {
      randomIdList.push(
        `${info.matCode}_${info.batchNo}_${info.moveFrontWorkshopCode}_${info.moveFrontWarehouse}`
      );
    });
    val.forEach((el) => {
      let obj = {};
      if (whMoveInventoryDetailList.value && whMoveInventoryDetailList.value.length) {
        if (!randomIdList.includes(el.randomId)) {
          obj.matCode = el.matCode;
          obj.matName = el.matName;
          obj.batchNo = el.batchNo;
          obj.packageUnit = el.packageUnit;
          obj.measureUnit = el.measureUnit;
          obj.packing = el.packing;
          obj.moveFrontStockNum = el.num;
          obj.moveNum = el.num;
          // 调拨前
          obj.moveFrontWorkSection = el.workShopCode;
          obj.moveFrontWorkSectionName = el.workshopName;
          obj.moveFrontPdcLine = el.lineCode;
          obj.moveFrontPdcLineName = el.lineName;
          obj.moveFrontProcessSection = el.sectionCode;
          obj.moveFrontProcessSectionName = el.sectionName;
          obj.moveFrontWorkshopCode = el.storehouseCode;
          obj.moveFrontWorkshopName = el.storehouseName;
          obj.moveFrontWarehouse = el.binCode;
          obj.moveFrontWarehouseName = el.binName;
          obj.erpOrderNo = el.erpOrderNo;
          obj.moveCode = form.value.moveCode;
          // 调拨后
          obj.moveAfterWorkSection = "";
          obj.moveAfterPdcLine = "";
          obj.moveAfterProcessSection = "";
          obj.moveAfterWorkshopCode = "";
          obj.moveAfterWarehouse = "";
          obj.frozenNum = el.frozenNum;
          obj.availableNum = floatSub(el.num,el.frozenNum)
          _newArr.push(obj);
        }
      } else {
        obj.matCode = el.matCode;
        obj.matName = el.matName;
        obj.batchNo = el.batchNo;
        obj.packageUnit = el.packageUnit;
        obj.measureUnit = el.measureUnit;
        obj.packing = el.packing;
        obj.moveFrontStockNum = el.num;
        obj.moveNum = el.num;
        // 调拨前
        obj.moveFrontWorkSection = el.workShopCode;
        obj.moveFrontWorkSectionName = el.workshopName;
        obj.moveFrontPdcLine = el.lineCode;
        obj.moveFrontPdcLineName = el.lineName;
        obj.moveFrontProcessSection = el.sectionCode;
        obj.moveFrontProcessSectionName = el.sectionName;
        obj.moveFrontWorkshopCode = el.storehouseCode;
        obj.moveFrontWorkshopName = el.storehouseName;
        obj.moveFrontWarehouse = el.binCode;
        obj.moveFrontWarehouseName = el.binName;
        obj.erpOrderNo = el.erpOrderNo;
        obj.moveCode = form.value.moveCode;
        // 调拨后
        obj.moveAfterWorkSection = "";
        obj.moveAfterPdcLine = "";
        obj.moveAfterProcessSection = "";
        obj.moveAfterWorkshopCode = "";
        obj.moveAfterWarehouse = "";
        obj.frozenNum = el.frozenNum || 0
        obj.availableNum = floatSub(el.num,el.frozenNum)
        _newArr.push(obj);
      }
    });
    whMoveInventoryDetailList.value =whMoveInventoryDetailList.value.concat(_newArr) ;
  }
}
/** 物料调拨明细删除按钮操作 */
function handleDeleteWhStorehouseInDetail(row, index) {
  proxy.$modal
    .confirm("是否确认移除序号为 " + (index + 1) + " 的数据项？")
    .then(() => {
      if (row.id) {
        delMoveInventoryDetail(row.id).then(() => {
          whMoveInventoryDetailList.value = whMoveInventoryDetailList.value.filter((item) => {
            return item.id !== row.id;
          });
          this.$modal.msgSuccess("移除成功");
        });
      } else {
        whMoveInventoryDetailList.value.splice(index, 1);
        this.$modal.msgSuccess("移除成功");
      }
    })
    .catch(() => {});
}

function getListWhStorehouseInDetail(code) {
  listMoveInventoryDetail({ pageSize: 10000, pageNum: 1, moveCode: code }).then((res) => {
    if (isBatch.value) {
      whMoveInventoryDetailList.value.push(...res.rows);
    } else {
      whMoveInventoryDetailList.value = res.rows;
    }
    if(whMoveInventoryDetailList.value.length){
      whMoveInventoryDetailList.value.forEach(item=>{
        item.availableNum = floatSub(item.moveFrontStockNum,item.frozenNum)
      })
    }
  });
}

onMounted(() => {
  reset();
  const { data, title } = attrs;
  binEditAble.value = true;
  operationTitle.value = title;
  if (title === "确认调拨") {
    editAble.value = false;
    actions.value = [
      {
        text: "取 消",
        theme: "",
        handle: () => {
          cancel();
        },
      },
      {
        text: "确 定",
        theme: "primary",
        handle: () => {
          submitForm();
        },
        loading: false,
      },
    ];
  } else if (title === "调拨详情") {
    editAble.value = false;
    binEditAble.value = false;
    actions.value = [];
  } else {
    editAble.value = true;
  }
  emit("setActions", actions.value);

  if (data) {
    getDetail(data.id);
  }
});
</script>

<style lang="scss">
.form-text {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
